package com.platform.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.constant.ApiConstant;
import com.platform.dao.*;
import com.platform.entity.AdVo;
import com.platform.entity.UserVo;
import com.platform.entity.res.*;
import com.platform.service.ApiAdService;
import com.platform.service.ApiUserService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.util.ApiUserUtils;
import com.platform.utils.DateUtils;
import com.platform.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 孝邻会接口
 * @Author jaalemon@163.com
 * @Date 2022/11/21 11:28
 * @Version 1.0
 */
@Api(tags = "2孝邻会公众号接口")
@RestController
@RequestMapping("/api/res")
@Slf4j
public class ApiResController extends ApiBaseAction {

    @Autowired
    private ApiResCaseMapper apiResCaseMapper;

    @Autowired
    private ApiResCaseJoinMapper apiResCaseJoinMapper;

    @Autowired
    private ApiResRecommendMapper apiResRecommendMapper;

    @Autowired
    private ApiResThanksMapper apiResThanksMapper;

    @Autowired
    private ApiResTrainMapper apiResTrainMapper;

    @Autowired
    private ApiResVisitMapper apiResVisitMapper;

    @Autowired
    private ApiUserService apiUserService;

    @Autowired
    private ApiAdService adService;

    @ApiOperation(value = "新闻资讯")
    @IgnoreAuth
    @GetMapping(value = "banner")
    public Object banner() {
        Map<String, Object> resultObj = new HashMap<>();

        Map<String, Object> param = new HashMap<>();
        param.put("ad_position_id", 2);
        List<AdVo> banner = adService.queryList(param);
        resultObj.put("banner", banner);

        return toResponsSuccess(resultObj);
    }

//    @IgnoreAuth
    @ApiOperation(value = "发布需求")
    @PostMapping("postCase")
    public Object postCase(@LoginUser UserVo loginUser, @RequestBody ResCase resCase) {
        if(StringUtils.isEmpty(resCase.getMobile())){
            return toResponsFail("联系电话不能为空！");
        }

        if(StringUtils.isEmpty(resCase.getEndTime())){
            return toResponsFail("截止时间不能为空！");
        }

        resCase.setAddTime(new Date());
        resCase.setStatus(1);// 默认进行中
        resCase.setUserId(loginUser.getUserId());

        apiResCaseMapper.insert(resCase);

        return toResponsSuccess("需求发布成功！");
    }

//    @IgnoreAuth
    @ApiOperation(value = "发起对接")
    @PostMapping("sendJoin")
    public Object sendJoin(@LoginUser UserVo loginUser, @RequestParam("caseId") Integer caseId,
                           @RequestParam("joinDesc") String joinDesc) {

        if(StringUtils.isEmpty(joinDesc)){
            return toResponsFail("对接说明不能为空！");
        }

        ResCase resCase = apiResCaseMapper.selectById(caseId);
        if(resCase == null){
            return toResponsFail("找不到您要对接的需求！");
        }
        if(loginUser.getUserId().equals(resCase.getUserId())){
            return toResponsFail("不能对接自己的需求！");
        }

        ResCaseJoin join = new ResCaseJoin();
        join.setCaseId(caseId);
        join.setJoinDesc(joinDesc);
        join.setJoinTime(new Date());
        join.setUserJoinId(loginUser.getUserId());
        join.setStatus(1);// 默认等待对接

        apiResCaseJoinMapper.insert(join);

        return toResponsSuccess("发起对接成功！");
    }

    @IgnoreAuth
    @ApiOperation(value = "热门需求")
    @GetMapping(value = "hotCases")
    public Object hotCases(@LoginUser UserVo loginUser, @RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        //查询列表数据
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", size);
        Query query = new Query(params);

        List<ResCase> resCases = apiResCaseMapper.pageList(query);

        int total = apiResCaseMapper.queryTotal(query);

        if(!CollectionUtils.isEmpty(resCases)){
            for (ResCase resCase : resCases) {
                resCase.setAddTimeStr(DateUtils.format(resCase.getAddTime(), "MM-dd HH:mm"));
                UserVo userVo = apiUserService.queryObject(resCase.getUserId());
                if(StringUtils.isEmpty(userVo.getRealName())){
                    resCase.setUserName(userVo.getNickname());
                }else{
                    resCase.setUserName(userVo.getRealName());
                }
                resCase.setCompanyName(userVo.getCompanyName());
                resCase.setUserIcon(userVo.getAvatar());
            }
        }

        ApiPageUtils pageUtil = new ApiPageUtils(resCases, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }

    @IgnoreAuth
    @ApiOperation(value = "需求详情")
    @PostMapping("caseDetail")
    public Object caseDetail(@LoginUser UserVo loginUser, @RequestParam("caseId") Integer caseId) {
        ResCase resCase = apiResCaseMapper.selectById(caseId);
        if(resCase != null){
            List<ResCaseJoin> joinList = apiResCaseJoinMapper.selectList(new QueryWrapper<ResCaseJoin>().eq("case_id", resCase.getId()));
            if(!CollectionUtils.isEmpty(joinList)){
                for(ResCaseJoin join : joinList){
                    UserVo userVo = apiUserService.queryObject(join.getUserJoinId());
                    if(StringUtils.isEmpty(userVo.getRealName())){
                        join.setJoinUserName(userVo.getNickname());
                    }else{
                        join.setJoinUserName(userVo.getRealName());
                    }
                    join.setJoinCompanyName(userVo.getCompanyName());
                    join.setJoinUserIcon(userVo.getAvatar());
                }
            }
            resCase.setJoinList(joinList);

            resCase.setAddTimeStr(DateUtils.format(resCase.getAddTime(), "MM-dd HH:mm"));
            UserVo userVo = apiUserService.queryObject(resCase.getUserId());
            if(StringUtils.isEmpty(userVo.getRealName())){
                resCase.setUserName(userVo.getNickname());
            }else{
                resCase.setUserName(userVo.getRealName());
            }
            resCase.setCompanyName(userVo.getCompanyName());
            resCase.setUserIcon(userVo.getAvatar());
        }
        return toResponsSuccess(resCase);
    }

//    @IgnoreAuth
    @ApiOperation(value = "添加引荐单")
    @PostMapping("addRecommend")
    public Object addRecommend(@LoginUser UserVo loginUser, @RequestBody ResRecommend resRecommend) {
        if(resRecommend.getTargetUserId() == null){
            return toResponsFail("引荐的目标对象不能为空！");
        }

        resRecommend.setAddTime(new Date());
        // 当前用户引荐的
        resRecommend.setSourceUserId(loginUser.getUserId());

        Long userId = resRecommend.getTargetUserId();
        if(resRecommend.getTargetUserId() > ApiConstant.BASE_ID){
            userId = resRecommend.getTargetUserId() - ApiConstant.BASE_ID;
        }

        if(loginUser.getUserId().equals(userId)){
            return toResponsFail("引荐单接收人不能是自己！");
        }

        UserVo userVo = apiUserService.queryObject(userId);
        if(userVo == null){
            return toResponsFail("ID为["+resRecommend.getTargetUserId()+"]的用户不存在！");
        }
        resRecommend.setTargetUserId(userId);

        apiResRecommendMapper.insert(resRecommend);

        return toResponsSuccess("添加引荐单成功！");
    }

    //    @IgnoreAuth
    @ApiOperation(value = "引荐单列表")
    @GetMapping(value = "recommendPageList")
    public Object recommendPageList(@LoginUser UserVo loginUser, @RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "size", defaultValue = "10") Integer size,
                                 @RequestParam(value = "direction") String direction
    ) {
        //查询列表数据
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", size);

        // direction : in 我的来访， out 我的探访
        if("out".equals(direction)){
            params.put("sourceUserId", loginUser.getUserId());
        }else{
            params.put("targetUserId", loginUser.getUserId());
        }

        Query query = new Query(params);

        List<ResRecommend> resultList = apiResRecommendMapper.pageList(query);

        if(!CollectionUtils.isEmpty(resultList)){
            for (ResRecommend result : resultList) {
                if(StringUtils.isEmpty(loginUser.getRealName())){
                    result.setOwnerName(loginUser.getNickname());
                }else{
                    result.setOwnerName(loginUser.getRealName());
                }

                result.setDirection(direction);
                result.setAddTimeStr(DateUtils.format(result.getAddTime(), "yyyy-MM-dd HH:mm"));

                Long userId = 0L;
                if("out".equals(direction)){
                    userId = result.getTargetUserId();;
                }else{
                    userId = result.getSourceUserId();
                }
                UserVo userVo = apiUserService.queryObject(userId);
                if(StringUtils.isEmpty(userVo.getRealName())){
                    result.setUserName(userVo.getNickname());
                }else{
                    result.setUserName(userVo.getRealName());
                }
                result.setCompanyName(userVo.getCompanyName());
                result.setUserIcon(userVo.getAvatar());
                result.setLevelName(ApiUserUtils.getLevelName(userVo.getUser_level_id()));
            }
        }

        int total = apiResRecommendMapper.queryTotal(query);

        ApiPageUtils pageUtil = new ApiPageUtils(resultList, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }

    //    @IgnoreAuth
    @ApiOperation(value = "添加感谢函")
    @PostMapping("addThanks")
    public Object addThanks(@LoginUser UserVo loginUser, @RequestBody ResThanks resThanks) {
        if(resThanks.getTargetUserId() == null){
            return toResponsFail("感谢函接收人不能为空！");
        }

        resThanks.setAddTime(new Date());
        // 当前用户
        resThanks.setSourceUserId(loginUser.getUserId());

        Long userId = resThanks.getTargetUserId();
        if(resThanks.getTargetUserId() > ApiConstant.BASE_ID){
            userId = resThanks.getTargetUserId() - ApiConstant.BASE_ID;
        }

        if(loginUser.getUserId().equals(userId)){
            return toResponsFail("感谢函接收人不能是自己！");
        }

        UserVo userVo = apiUserService.queryObject(userId);
        if(userVo == null){
            return toResponsFail("ID为["+resThanks.getTargetUserId()+"]的用户不存在！");
        }
        resThanks.setTargetUserId(userId);

        apiResThanksMapper.insert(resThanks);

        return toResponsSuccess("添加感谢函成功！");
    }

//    @IgnoreAuth
    @ApiOperation(value = "感谢函列表")
    @GetMapping(value = "thanksPageList")
    public Object thanksPageList(@LoginUser UserVo loginUser, @RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "size", defaultValue = "10") Integer size,
                                @RequestParam(value = "direction") String direction
    ) {
        //查询列表数据
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", size);

        // direction : in 我的来访， out 我的探访
        if("out".equals(direction)){
            params.put("sourceUserId", loginUser.getUserId());
        }else{
            params.put("targetUserId", loginUser.getUserId());
        }

        Query query = new Query(params);

        List<ResThanks> resultList = apiResThanksMapper.pageList(query);

        if(!CollectionUtils.isEmpty(resultList)){
            for (ResThanks result : resultList) {
                if(StringUtils.isEmpty(loginUser.getRealName())){
                    result.setOwnerName(loginUser.getNickname());
                }else{
                    result.setOwnerName(loginUser.getRealName());
                }

                result.setDirection(direction);
                result.setAddTimeStr(DateUtils.format(result.getAddTime(), "yyyy-MM-dd HH:mm"));

                Long userId = 0L;
                if("out".equals(direction)){
                    userId = result.getTargetUserId();;
                }else{
                    userId = result.getSourceUserId();
                }
                UserVo userVo = apiUserService.queryObject(userId);
                if(StringUtils.isEmpty(userVo.getRealName())){
                    result.setUserName(userVo.getNickname());
                }else{
                    result.setUserName(userVo.getRealName());
                }
                result.setCompanyName(userVo.getCompanyName());
                result.setUserIcon(userVo.getAvatar());
                result.setLevelName(ApiUserUtils.getLevelName(userVo.getUser_level_id()));
            }
        }

        int total = apiResThanksMapper.queryTotal(query);

        ApiPageUtils pageUtil = new ApiPageUtils(resultList, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }

//    @IgnoreAuth
    @ApiOperation(value = "添加会员聚会记录")
    @PostMapping("addTrain")
    public Object addTrain(@LoginUser UserVo loginUser, @RequestBody ResTrain resTrain) {

        resTrain.setAddTime(new Date());
        resTrain.setUserId(loginUser.getUserId());

        apiResTrainMapper.insert(resTrain);

        return toResponsSuccess("添加会员聚会记录成功！");
    }

//    @IgnoreAuth
    @ApiOperation(value = "会员聚会记录列表")
    @GetMapping(value = "trainPageList")
    public Object trainPageList(@LoginUser UserVo loginUser, @RequestParam(value = "page", defaultValue = "1") Integer page,
                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        //查询列表数据
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", size);
        params.put("userId", loginUser.getUserId());
        Query query = new Query(params);

        List<ResTrain> resultList = apiResTrainMapper.pageList(query);

        int total = apiResTrainMapper.queryTotal(query);

        ApiPageUtils pageUtil = new ApiPageUtils(resultList, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }

//    @IgnoreAuth
    @ApiOperation(value = "添加探访记录单")
    @PostMapping("addVisit")
    public Object addVisit(@LoginUser UserVo loginUser, @RequestBody ResVisit resVisit) {

        resVisit.setAddTime(new Date());
        // 当前用户
        resVisit.setSourceUserId(loginUser.getUserId());

        // 被探访的用户id
        Long userId = resVisit.getTargetUserId();
        if(resVisit.getTargetUserId() > ApiConstant.BASE_ID){
            userId = resVisit.getTargetUserId() - ApiConstant.BASE_ID;
        }

        if(loginUser.getUserId().equals(userId)){
            return toResponsFail("被探访的用户不能是自己！");
        }

        UserVo userVo = apiUserService.queryObject(userId);
        if(userVo == null){
            return toResponsFail("ID为["+resVisit.getTargetUserId()+"]的用户不存在！");
        }

        resVisit.setTargetUserId(userId);

        apiResVisitMapper.insert(resVisit);

        return toResponsSuccess("添加探访记录单成功！");
    }

//    @IgnoreAuth
    @ApiOperation(value = "探访记录单列表")
    @GetMapping(value = "visitPageList")
    public Object visitPageList(@LoginUser UserVo loginUser, @RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "size", defaultValue = "10") Integer size,
                                @RequestParam(value = "direction") String direction
                                ) {
        //查询列表数据
        Map params = new HashMap();
        params.put("page", page);
        params.put("limit", size);

        // direction : in 我的来访， out 我的探访
        String directionParam = direction;
        if("out".equals(direction)){
            params.put("sourceUserId", loginUser.getUserId());
        }else if("in".equals(direction)){
            params.put("targetUserId", loginUser.getUserId());
        }else{
            // all
            direction = "out";//显示一边
        }

        Query query = new Query(params);

        List<ResVisit> resultList = apiResVisitMapper.pageList(query);

        if(!CollectionUtils.isEmpty(resultList)){
            for (ResVisit result : resultList) {
                if("all".equals(directionParam)){
                    UserVo userVo = apiUserService.queryObject(result.getSourceUserId());
                    if(StringUtils.isEmpty(userVo.getRealName())){
                        result.setOwnerName(userVo.getNickname());
                    }else{
                        result.setOwnerName(userVo.getRealName());
                    }
                }else{
                    if(StringUtils.isEmpty(loginUser.getRealName())){
                        result.setOwnerName(loginUser.getNickname());
                    }else{
                        result.setOwnerName(loginUser.getRealName());
                    }
                }

                if(!StringUtils.isEmpty(result.getPicUrl())){
                    result.setPicUrlArr(result.getPicUrl().split(","));
                }

                result.setDirection(direction);
                result.setAddTimeStr(DateUtils.format(result.getAddTime(), "yyyy-MM-dd HH:mm"));

                Long userId = 0L;
                if("out".equals(direction)){
                    userId = result.getTargetUserId();;
                }else{
                    userId = result.getSourceUserId();
                }
                UserVo userVo = apiUserService.queryObject(userId);
                if(StringUtils.isEmpty(userVo.getRealName())){
                    result.setUserName(userVo.getNickname());
                }else{
                    result.setUserName(userVo.getRealName());
                }
                result.setCompanyName(userVo.getCompanyName());
                result.setUserIcon(userVo.getAvatar());

                result.setLevelName(ApiUserUtils.getLevelName(userVo.getUser_level_id()));
            }
        }

        int total = apiResVisitMapper.queryTotal(query);

        ApiPageUtils pageUtil = new ApiPageUtils(resultList, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }


    @ApiOperation(value = "首页统计")
    @GetMapping(value = "indexSummary")
    public Object indexSummary(@LoginUser UserVo loginUser){
        Map result = new HashMap();

        List<Integer> footmarkList = apiResCaseMapper.queryFootmarkByWeek(loginUser.getUserId());
        result.put("footmarkList", footmarkList);

        List<Long> totalList = apiResCaseMapper.queryFootmarkTotal(loginUser.getUserId());
        result.put("totalList", totalList);

        return toResponsSuccess(result);
    }


}
